package org.oschina.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.oschina.Message;
import org.oschina.ResultUtil;
import org.oschina.bean.Result;
import org.oschina.helper.JsonHelper;
import org.oschina.security.AuthenticationException;
import org.oschina.util.PrintUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerExceptionResolverComposite;

@Component
public class ControllerExceptionHandler extends HandlerExceptionResolverComposite {
	
	private final static Logger logger=LoggerFactory.getLogger(ControllerExceptionHandler.class);
	
	@Override
	public ModelAndView resolveException(HttpServletRequest request,HttpServletResponse response,Object handler,Exception exception)
	{
		//权限不足的处理
		if(exception instanceof AuthenticationException)
		{
			return putErrorMessage(handler,request,response,Message.ERROR_UNAUTHORIZED);
		}
		//普通异常处理
		else
		{
			//exception.printStackTrace();
			logger.error("",exception);
			return putErrorMessage(handler,request,response,Message.ERROR_APP_ERROR);
		}
	}
	
	private ModelAndView putErrorMessage(Object handler,HttpServletRequest request,HttpServletResponse response,String message)
	{
		HandlerMethod handle=(HandlerMethod)handler;
		ModelAndView modelAndView=new ModelAndView();
		//判断是否为结果输出
		if(handle.getMethod().getReturnType().equals(Result.class))
		{
			PrintUtil.print(JsonHelper.toJson(ResultUtil.getFailure(message)),"application/json", response);
		}

		return modelAndView;
	}
}